#通过ssh获取交换机的接口状态和接口信息
#不支持snmp的情况下使用此方法
#版本v1.0.2

import paramiko
from openpyxl import Workbook,load_workbook
import time
import re
from concurrent.futures import ThreadPoolExecutor

def device_info():
    """创建ssh客户端"""
    #  1.从excel中获取的设备信息
    wb = load_workbook("./host.xlsx")
    ws = wb["Switch"]
    #  4.创建一个空的excel表
    wb1 = Workbook()
    #  2.创建进程池
    pool = ThreadPoolExecutor(ws.max_row)
    #  3.获取设备信息
    for row in range(2, ws.max_row + 1):
        hostname = ws.cell(row, 1).value
        ip = ws.cell(row, 2).value
        user = ws.cell(row, 3).value
        passwd = ws.cell(row, 4).value
        company = ws.cell(row, 5).value
        version = ws.cell(row, 6).value
        ws1 = wb1.create_sheet(hostname)
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(hostname=ip, port=22, username=user, password=passwd)
        client = ssh_client.invoke_shell()
        pool.submit(ssh_client)
        print(f"{ip}连接成功！")
    except:
        print(f"{ip}连接失败！")
    else:
        #  根据设备型号关闭分屏功能
        if company == "Huawei":
            client.send("n\n")
            client.send('screen-length 0 temporary\n')
        elif company == "H3C":
            client.send("n\n")
            client.send('screen-length disable\n')
        #  获取设备所有的接口信息
        client.send('dis cu int | in int\n')
        time.sleep(10)
        interface_info = client.recv(999999).decode()
        #  筛选出设备的接口名称
        interface_list = re.findall("\S+\s(\S+\/\d+)", interface_info)
        print(f"获取到 {ip} 设备有{str(len(interface_list))}个接口")
        #  添加表标题
        ws1.append(['接口', '接口类型', 'pvid', '接口状态','接口描述', '采集时间'])
        #  循环遍历出接口的信息
        for interface in interface_list:
            client.send(f'display interface {interface} \n')
            time.sleep(1)
            interface_info1 = client.recv(999999).decode()
            try:
                if company == "H3C":
                    interface_type = re.findall('Port link-type:\s+(\w+)', interface_info1)
                    interface_pvid = re.findall('PVID:\s+(\d+)', interface_info1)
                    interface_desc = re.findall('Description: (.*\S+)', interface_info1)
                    if version == "H3C V5":
                        interface_state = re.findall('current state: (\S+)', interface_info1)
                    elif version == "H3C V7":
                        interface_state = re.findall('Current state:(.*\w+)', interface_info1)
                elif company == "Huawei":
                    interface_state = re.findall('Line protocol current state : (\S+)', interface_info1)
                    interface_type = re.findall('Link-type : (\w+)', interface_info1)
                    interface_pvid = re.findall('PVID :\s+(\d+)', interface_info1)
                    interface_desc = re.findall('Description: (.*\S+)', interface_info1)
            except:
                print(f"{ip}excel写入失败！")
            else:
                ws1.cell(interface_list.index(interface) + 2, 1).value = str(interface)
                ws1.cell(interface_list.index(interface) + 2, 2).value = "".join(interface_type)
                ws1.cell(interface_list.index(interface) + 2, 3).value = "".join(interface_pvid)
                ws1.cell(interface_list.index(interface) + 2, 4).value = "".join(interface_state)
                ws1.cell(interface_list.index(interface) + 2, 5).value = "".join(interface_desc)
                ws1.cell(interface_list.index(interface) + 2, 6).value = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
                print(f"收集到{interface}接口信息")
        print(f"{hostname}接口采集完成！")
    finally:
        ssh_client.close()

    pool.shutdown(wait=True)

    now = time.strftime("%Y-%m-%d %H.%M.%S",time.localtime())
    wb1.save(f"./{now}接口采集表.xlsx")











def main():

    start = time.time()
    device_info()
    end = time.time()
    print("所有设备采集完成，用时%ds" %(end-start))

if __name__ == "__main__":
    main()
